package net.tngou.tpage.action.api;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.text.translate.NumericEntityUnescaper;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import net.tngou.tpage.action.BaseAction;
import net.tngou.tpage.enums.LevelEnum;
import net.tngou.tpage.pojo.User;
import net.tngou.tpage.service.UserService;
import net.tngou.tpage.util.DigestMD;
import net.tngou.tpage.util.OAuthUtil;


/**
 * 用户登录
 * @author tngou@tngou.net
 *
 */
public class LoginApi extends BaseAction {
	@SuppressWarnings("serial")
	@Override
	public void execute() throws ServletException, IOException {
		String account=request.getParameter("account");//账户
		String password=request.getParameter("password");//密码
		String save_login=request.getParameter("save_login");//是否在线
		
		if(isEmpty(account,password)){
			run_false("请求参数不正确！");return;
		}
		user=new User().get(new HashMap<String,Object>(){{
			put("account", account);
			put("password", DigestMD.MD5(password));//密码做MD5
		}});

		if(user!=null)
		{
			
			String access_token = OAuthUtil.Access_token(user.getAccount(), user.getPassword()); //
			String refresh_token = OAuthUtil.Refresh_token(user.getAccount());
			
			if(save_login==null) //用于兼容web端处理
			{
				response.addAutoLoginCookie(access_token);//临时 Cookie
			}else
			{
				response.addAutoLoginCookie(60*60*24*365, access_token);//保存1年的Cookie
			}	
			UserService service = new UserService();
			service.saveLogin(access_token, refresh_token, user);
			user.setAccess_token(access_token);
			user.setRefresh_token(refresh_token);
			session.setUser(user);
			run_success(access_token);
		}else
		{
			run_false("用户验证失败！");
		}
	}
	
	
}
